package com.atguigu.yygh.common.exception;

import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
//@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    //返回json格式的结果
    //@ResponseBody
    public R error(Exception e){
//        log.info("error(Exception e)");
        //打印错误跟踪栈
//        e.printStackTrace();
        //前端返回统一错误结果
        log.error(ExceptionUtils.getStackTrace(e));
        return R.error();
    }

    @ExceptionHandler(ArithmeticException.class)
    public R error(ArithmeticException e){

//        log.info("error(ArithmeticException e)");
//        e.printStackTrace();
        log.error(ExceptionUtils.getStackTrace(e));
        return R.error().message("算数错误").code(ResultCode.ARTHMETIC_ERROR);
    }

    @ExceptionHandler(BadSqlGrammarException.class)
    public R error(BadSqlGrammarException e){
//        log.info("error(BadSqlGrammarException e)");
//        e.printStackTrace();
        log.error(ExceptionUtils.getStackTrace(e));
        return R.error().message("SQL语法错误").code(ResultCode.SQL_GRAMMAR_ERROR);
    }

    @ExceptionHandler(YyghException.class)
    public R error(YyghException e){
//        log.info("error(YyghException e)");
//        log.info("error message:" + e.getMessage());
        //e.printStackTrace();
        log.error(ExceptionUtils.getStackTrace(e));
        return R.error().message(e.getMsg()).code(e.getCode());
    }
}
